<template>
    <el-form ref="formRef" :model="modelValue" :rules="rules" :label-width="labelWidth" class="g-form">
      <el-form-item v-for="item in formConfig" :key="item.prop" :label="item.label" :prop="item.prop"
        :rules="item.rules">
        <!-- 输入框 -->
        <el-input v-if="item.type === 'input'" v-model="modelValue[item.prop]" :placeholder="item.placeholder" />
  
        <!-- 文本框 -->
        <el-input v-if="item.type === 'textarea'" v-model="modelValue[item.prop]" type="textarea" :rows="item.rows || 3"
          :placeholder="item.placeholder" />
  
        <!-- 选择框 -->
        <el-select v-if="item.type === 'select'" v-model="modelValue[item.prop]" :multiple="item.multiple"
          :placeholder="item.placeholder" class="w-full">
          <el-option v-for="option in item.options || getOptions(item)" :key="option.value" :label="option.label"
            :value="option.value" />
        </el-select>
  
        <!-- 日期选择器 -->
        <el-date-picker v-if="item.type === 'date'" v-model="modelValue[item.prop]" type="date" format="YYYY-MM-DD"
          value-format="YYYY-MM-DD" :placeholder="item.placeholder" style="width: 100%" />
  
        <!-- 开关 -->
        <el-switch v-if="item.type === 'switch'" v-model="modelValue[item.prop]" :active-text="item.activeText"
          :inactive-text="item.inactiveText" />
  
        <!-- 单选框组 -->
        <el-radio-group v-if="item.type === 'radio'" v-model="modelValue[item.prop]">
          <el-radio v-for="option in item.options || getOptions(item)" :key="option.value" :label="option.value">
            {{ option.label }}
          </el-radio>
        </el-radio-group>
  
        <!-- 多选框组 -->
        <el-checkbox-group v-if="item.type === 'checkbox'" v-model="modelValue[item.prop]">
          <el-checkbox v-for="option in item.options || getOptions(item)" :key="option.value" :label="option.value">
            {{ option.label }}
          </el-checkbox>
        </el-checkbox-group>
  
        <!-- 文件上传 -->
        <el-upload v-if="item.type === 'upload'" :action="item.action" :multiple="item.multiple" :limit="item.limit"
          :on-success="(res) => handleUploadSuccess(res, item)" :on-error="handleUploadError"
          :on-exceed="handleExceed" :file-list="modelValue[item.prop]">
          <el-button type="primary">点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip">
              {{ item.tip || `只能上传 ${item.accept || '*'} 文件` }}
            </div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  
  const props = defineProps({
    modelValue: {
      type: Object,
      required: true
    },
    formConfig: {
      type: Array,
      required: true
    },
    labelWidth: {
      type: String,
      default: '140px'
    },
    rules: {
      type: Object,
      default: () => ({})
    }
  })
  
  const emit = defineEmits(['update:modelValue', 'validate'])
  
  const formRef = ref(null)
  
  // 处理远程选项数据
  const optionsCache = ref({})
  
  const getOptions = async (item) => {
    if (!item.remote) return []
    
    if (optionsCache.value[item.prop]) {
      return optionsCache.value[item.prop]
    }
  
    try {
      const res = await item.remote()
      optionsCache.value[item.prop] = res
      return res
    } catch (error) {
      console.error('获取选项数据失败:', error)
      return []
    }
  }
  
  // 文件上传相关处理
  const handleUploadSuccess = (res, item) => {
    if (item.multiple) {
      if (!Array.isArray(props.modelValue[item.prop])) {
        props.modelValue[item.prop] = []
      }
      props.modelValue[item.prop].push(res)
    } else {
      props.modelValue[item.prop] = res
    }
    emit('update:modelValue', props.modelValue)
    ElMessage.success('上传成功')
  }
  
  const handleUploadError = () => {
    ElMessage.error('上传失败')
  }
  
  const handleExceed = (files, uploadFiles) => {
    ElMessage.warning(`最多只能上传 ${uploadFiles.length} 个文件`)
  }
  
  // 表单验证方法
  const validate = async () => {
    if (!formRef.value) return false
    return await formRef.value.validate()
  }
  
  // 暴露方法给父组件
  defineExpose({
    validate,
    formRef
  })
  
  onMounted(() => {
    // 初始化远程数据
    props.formConfig.forEach(item => {
      if (item.remote) {
        getOptions(item)
      }
    })
  })
  </script>
  
  <style lang="less" scoped>
  .g-form {
    :deep(.el-select) {
      width: 100%;
    }
  
    :deep(.el-upload) {
      width: 100%;
    }
  
    :deep(.el-upload__tip) {
      line-height: 1.2;
      padding: 4px 0;
      color: #909399;
    }
  }
  </style>